package Controller;

import DAO.UserDAO;
import Domain.UserEntity;
import Util.HibernateUtil;
import Util.SocketClient;
import Util.SocketServer;
import org.hibernate.Session;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
@EnableAutoConfiguration
@SpringBootApplication
public class Application {

    SocketServer server;
    SocketClient client;

    @RequestMapping("/hello")
    public String hello(){
        try {
            Session session = HibernateUtil.getSession();
            UserDAO userdao = new UserDAO();

//          数据库写操作
//
//            UserEntity user = new UserEntity();
//            user.setId(2);
//            user.setUsername("付");
//            user.setPassword("123");
//            user.setAge(22);
//
//            session.beginTransaction();
//            session.save(user);
//            session.getTransaction().commit();
//
//            return "数据保存成功";

//          数据库读操作
            session.beginTransaction();
            UserEntity user = (UserEntity)session.get(UserEntity.class,1);
            session.close();

            return "hello," + user.getUsername();

//            return "hello,world!";

        }catch (Exception e){
            return "Error!";
        }
    }


    @RequestMapping("/server_start")
    public void server_socket(){
        server = new SocketServer();
        server.server_start();
    }

    @RequestMapping("/server_end")
    public void server_end(){
        server.server_end();
    }

    @RequestMapping("/server_accept")
    public void server_accept(){
        server.server_accept();
    }

    @RequestMapping("/client_start")
    @ResponseBody
    public String client_socket(@RequestParam String command){
        client = new SocketClient();
        return client.oneClient(command);
    }


    @RequestMapping("/index")
    public ModelAndView index() {
        return new ModelAndView("index");
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }
}
